package goodbaby.dklt.activity;

import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.classic.core.activity.BaseActivity;
import com.classic.core.utils.FileUtil;
import com.classic.core.utils.ImageUtils;
import com.classic.core.utils.KeyBoardUtil;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;
import com.tgd.gbb.uikit.ui.dialog.BottomSelectDialog;
import com.tgd.gbb.uikit.ui.widget.toast.LoadToast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import goodbaby.dklt.Const;
import goodbaby.dklt.GbbPreferences;
import goodbaby.dklt.R;
import goodbaby.dklt.bean.SpinnerBean;
import goodbaby.dklt.customerview.AtlasSeeActivity;
import goodbaby.dklt.customerview.ImageLoaderUtil;
import goodbaby.dklt.customerview.multi_image_selector.MultiImageSelectorActivity;
import goodbaby.dklt.emotion.DisplayUtils;
import goodbaby.dklt.emotion.EmotionGvAdapter;
import goodbaby.dklt.emotion.EmotionPagerAdapter;
import goodbaby.dklt.emotion.EmotionUtils;
import goodbaby.dklt.emotion.StringUtils;

/**
 * Created by Jayden on 2016/4/26 17:22.
 *
 * @version V1.0
 * @Title: SendParentsCircleActivity
 * @Description: 发布家校互通页面
 */
public class SendParentsCircleActivity extends BaseActivity implements View.OnLayoutChangeListener, AdapterView.OnItemClickListener {
    private static final int REQUEST_IMAGE = 2;
    private final int PIC_MAX_LENGTH = 9;
    private ImageView addFriend;
    private LinearLayout llRoot;
    //    private ImageView vedioBg;
    private String bitmapPath;
    private Context context;
    private ArrayList<String> currentPath = new ArrayList();
    private EditText edtContent;
    private TextView tvLimit;
    private LinearLayout friendLL;
    private ImageView ivBack;
    private List<FriendImageView> listFriend = new ArrayList();
    private ArrayList<String> mSelectPath;
    private int msgType;//0:视频，1:家校互通消息（图片）,2：食谱/课程,3：教务公告/工作汇报
    private ArrayList<String> selectedPictureAll = new ArrayList();
    private TextView tvSend;
    private TextView tvTitle;
    private Bitmap vedioBitmap;
    private File vedioFile;
    private String vedioFilePath;
    private RelativeLayout rlSelectTime, rlMsgInput;
    private HorizontalScrollView hsImage;
    private TextView tvTime;
    private BottomSelectDialog dialog;
    private int role;
    private String isWeek, isRC;
    private List<SpinnerBean> classes = new ArrayList<SpinnerBean>();
    private List<SpinnerBean> adminroels = new ArrayList<SpinnerBean>();
    private List<SpinnerBean> students = new ArrayList<SpinnerBean>();
    private Spinner classSpinner, studentsSpinner;
    private LinearLayout llClassSpinner, llStudentSpinner;
    private int currentClassId, currentStudentId, currentAdminroelId;
    private int isWork;

    private int screenHeight = 0;
    private int keyHeight = 0;
    private ImageView btnExp;
    private LinearLayout ll_emotion_dashboard;
    private ViewPager vp_emotion_dashboard;
    private EmotionPagerAdapter emotionPagerGvAdapter;



    /**
     * 初始化表情面板内容
     */
    private void initEmotion() {
        // 获取屏幕宽度
        int gvWidth = DisplayUtils.getScreenWidthPixels(this);
        // 表情边距
        int spacing = DisplayUtils.dp2px(this, 8);
        // GridView中item的宽度
        int itemWidth = (gvWidth - spacing * 8) / 7;
        int gvHeight = itemWidth * 3 + spacing * 4;

        List<GridView> gvs = new ArrayList<GridView>();
        List<String> emotionNames = new ArrayList<String>();
        // 遍历所有的表情名字
        for (String emojiName : EmotionUtils.emojiMap.keySet()) {
            emotionNames.add(emojiName);
            // 每20个表情作为一组,同时添加到ViewPager对应的view集合中
            if (emotionNames.size() == 20) {
                GridView gv = createEmotionGridView(emotionNames, gvWidth, spacing, itemWidth, gvHeight);
                gvs.add(gv);
                // 添加完一组表情,重新创建一个表情名字集合
                emotionNames = new ArrayList<String>();
            }
        }

        // 检查最后是否有不足20个表情的剩余情况
        if (emotionNames.size() > 0) {
            GridView gv = createEmotionGridView(emotionNames, gvWidth, spacing, itemWidth, gvHeight);
            gvs.add(gv);
        }

        // 将多个GridView添加显示到ViewPager中
        emotionPagerGvAdapter = new EmotionPagerAdapter(gvs);
        vp_emotion_dashboard.setAdapter(emotionPagerGvAdapter);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(gvWidth, gvHeight);
        vp_emotion_dashboard.setLayoutParams(params);
    }


    /**
     * 创建显示表情的GridView
     */
    private GridView createEmotionGridView(List<String> emotionNames, int gvWidth, int padding, int itemWidth, int gvHeight) {
        // 创建GridView
        GridView gv = new GridView(this);
        gv.setBackgroundColor(Color.rgb(233, 233, 233));
        gv.setSelector(android.R.color.transparent);
        gv.setNumColumns(7);
        gv.setPadding(padding, padding, padding, padding);
        gv.setHorizontalSpacing(padding);
        gv.setVerticalSpacing(padding);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(gvWidth, gvHeight);
        gv.setLayoutParams(params);
        // 给GridView设置表情图片
        EmotionGvAdapter adapter = new EmotionGvAdapter(this, emotionNames, itemWidth);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(this);
        return gv;
    }

    private void bitmapToPath() {
        vedioBitmap = ThumbnailUtils.createVideoThumbnail(vedioFilePath, 1);
        vedioBitmap = ThumbnailUtils.extractThumbnail(vedioBitmap, 400, 400, 2);
        Drawable drawable = ImageUtils.bitmapToDrawable(vedioBitmap);
        addFriend.setImageDrawable(drawable);
//        File localFile2 = null;
//        if (vedioBitmap != null) {
//            File localFile1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/goodbaby/VedioImage/");
//            if (!localFile1.exists())
//                localFile1.mkdirs();
//            bitmapPath = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/goodbaby/VedioImage/temp" + "_cropped" + ".jpg");
//            localFile2 = new File(bitmapPath);
//        }
//        try {
//            localFile2.createNewFile();
//            FileOutputStream localFileOutputStream = new FileOutputStream(localFile2);
//            vedioBitmap.compress(Bitmap.CompressFormat.JPEG, 50, localFileOutputStream);
//            localFileOutputStream.flush();
//            localFileOutputStream.close();
//            ImageLoaderUtil.loadLocalUrl(bitmapPath, addFriend);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    private void changeImageToBitmap(ArrayList<String> images) {
        for (String image : images) {
            String theLarge;
            String theThumbnail = "";
            File imgFile;
            String imgName = FileUtil.getFileName(image);
            theLarge = image;
            if (imgName != null) {
                Bitmap bitmap = ImageUtils.loadImgThumbnail(SendParentsCircleActivity.this,
                        imgName,
                        MediaStore.Images.Thumbnails.MICRO_KIND);

//                if (bitmap != null) {
                String savePath = Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/goodbaby/Camera/";
                File savedir = new File(savePath);
                if (!savedir.exists()) {
                    savedir.mkdirs();
                }
                String largeFileName = FileUtil.getFileName(theLarge);
                String largeFilePath = savePath + largeFileName;
                // 判断是否已存在缩略图
                if (largeFileName.startsWith("thumb_")
                        && new File(largeFilePath).exists()) {
                    theThumbnail = largeFilePath;
                    imgFile = new File(theThumbnail);
                } else {
                    // 生成上传的800宽度图片
                    String thumbFileName = "thumb_" + largeFileName;
                    theThumbnail = savePath + thumbFileName;
                    if (new File(theThumbnail).exists()) {
                        imgFile = new File(theThumbnail);
                    } else {
                        try {
                            // 压缩上传的图片
                            ImageUtils.createImageThumbnail(SendParentsCircleActivity.this,
                                    theLarge, theThumbnail, 800, 80);
                            imgFile = new File(theThumbnail);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
//                }
                currentPath.add(theThumbnail);
            }

        }
    }

    private void notyPicChange() {
        if (msgType == 2) {
            if (selectedPictureAll.size() > 0) {
                addFriend.setVisibility(View.GONE);
            } else {
                addFriend.setVisibility(View.VISIBLE);
            }
        } else {
            if (selectedPictureAll.size() > 8) {
                addFriend.setVisibility(View.GONE);
            } else {
                addFriend.setVisibility(View.VISIBLE);
            }
        }
    }

    private void submit() {
        String[] picPATHs = currentPath.toArray(new String[currentPath.size()]);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < currentPath.size(); i++) {
            sb.append(ImageUtils.bitmapToBase64(ImageUtils.getBitmapByPath(currentPath.get(i))) + "#jpg");
            if (i < currentPath.size() - 1) {
                sb.append("|");
            }
        }

        System.err.print(sb.toString());

        if (picPATHs.length > 9) {
            ToastUtil.showToast(context, "最多上传9张图片哦~");
        } else if (StringUtil.isEmpty(edtContent.getText().toString().trim())) {
            ToastUtil.showToast(context, "发送内容不能为空哦");
        } else {
            if (edtContent.getText().toString().trim().length() > 200) {
                ToastUtil.showToast(context, "不能超过200个字");
            } else {
//						loadingDialog.show();
                showToast();
                tvSend.setEnabled(false);
                ActionHelp.gbbPubMsg(SendParentsCircleActivity.this, 1, edtContent.getText().toString().trim(), sb.toString(), new ObjectCallback<String>() {
                    @Override
                    public void onSuccess(String response) {
                        success();
                    }

                    @Override
                    public void onError(int code) {
                        if (code == 301) {
                            Intent intent = new Intent(SendParentsCircleActivity.this, LoginActivity.class);
                            startActivity(intent);
                        } else {
                            closeToast(-1);
                            tvSend.setEnabled(true);
                            ToastUtil.showToast(context, "发布失败");
                        }
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        super.onError(code, errorMessage);
                        closeToast(-1);
                        tvSend.setEnabled(true);
                        ToastUtil.showToast(context, "发布失败");
                    }

                    @Override
                    public void onHttpError(int statusCode) {
                        super.onHttpError(statusCode);
                        closeToast(-1);
                        tvSend.setEnabled(true);
                        ToastUtil.showToast(context, "网络异常");
                    }

                    @Override
                    public Type getType() {
                        return new TypeToken<List<String>>() {
                        }.getType();
                    }
                });
            }
        }
    }


    private void vedioSubmit() {
        FileInputStream localFileInputStream = null;
        try {
            localFileInputStream = new FileInputStream(vedioFile);
            byte[] arrayOfByte = new byte[100 + (int) this.vedioFile.length()];
            String str = null;
            try {
                str = Base64.encodeToString(arrayOfByte, 0, localFileInputStream.read(arrayOfByte), 0);
            } catch (IOException e) {
                e.printStackTrace();
            }
            StringBuffer sb = new StringBuffer();
            sb.append(str).append("|");
            sb.append(ImageUtils.bitmapToBase64(vedioBitmap) + "#jpg");
            showToast();
            tvSend.setEnabled(false);
            ActionHelp.gbbPubMsg(this, 2, this.edtContent.getText().toString().trim(), sb.toString(), new ObjectCallback<String>() {

                public void onError(int code) {
                    if (code == 301) {
                        Intent intent = new Intent(SendParentsCircleActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        closeToast(-1);
                        tvSend.setEnabled(true);
                        ToastUtil.showToast(SendParentsCircleActivity.this.context, "发布失败");
                    }
                }

                public void onSuccess(String paramAnonymousString) {
                    success();
                }

                @Override
                public Type getType() {
                    return new TypeToken<String>() {
                    }.getType();
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    public int getLayoutResId() {
        return R.layout.activity_send_msg;
    }

    @Override
    public void initData() {
        super.initData();
        screenHeight = getWindowManager().getDefaultDisplay().getHeight();
        keyHeight = (screenHeight / 3);
        role = Integer.parseInt(GbbPreferences.getRole());
    }

    public void initView() {
        super.initView();
        msgType = getIntent().getIntExtra("msgType", 1);
        if (getIntent().getExtras().containsKey("vedioPath"))
            vedioFilePath = getIntent().getStringExtra("vedioPath");
        context = this;
        tvTitle = (TextView) findViewById(R.id.tv_common_title);
        tvSend = (TextView) findViewById(R.id.tv_common_leave_history);
        tvSend.setText("发送");
        tvSend.setVisibility(View.VISIBLE);
        tvSend.setOnClickListener(this);
        ivBack = (ImageView) findViewById(R.id.iv_common_back);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        rlSelectTime = (RelativeLayout) findViewById(R.id.rl_select_time);
        rlSelectTime.setOnClickListener(this);
        rlMsgInput = (RelativeLayout) findViewById(R.id.rl_msg_input);
        hsImage = (HorizontalScrollView) findViewById(R.id.hs_image);
        tvTime = (TextView) findViewById(R.id.tv_time);
//        vedioBg = (ImageView) findViewById(R.id.iv_vedio_bg);
//        vedioBg.setOnClickListener(this);
        addFriend = (ImageView) findViewById(R.id.iv_add_pic);
        addFriend.setOnClickListener(this);
        tvLimit = (TextView) findViewById(R.id.tv_limit);
        llRoot = (LinearLayout) findViewById(R.id.root_send_page);
        llRoot.addOnLayoutChangeListener(this);
        ll_emotion_dashboard = (LinearLayout) findViewById(R.id.ll_emotion_dashboard);
        vp_emotion_dashboard = (ViewPager) findViewById(R.id.vp_emotion_dashboard);
        btnExp = (ImageView) findViewById(R.id.btn_exp);
        btnExp.setOnClickListener(this);
        classSpinner = (Spinner) findViewById(R.id.spinner1);
        studentsSpinner = (Spinner) findViewById(R.id.spinner2);
        llClassSpinner = (LinearLayout) findViewById(R.id.ll_spinner1);
        llStudentSpinner = (LinearLayout) findViewById(R.id.ll_spinner2);
        edtContent = (EditText) findViewById(R.id.et_sendmsg);
        edtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int length = s.length();
                tvLimit.setText(length + "/200");
            }
        });
        friendLL = (LinearLayout) findViewById(R.id.ll_add_pic);
        if (msgType == 0) {
            tvTitle.setText("动态");
            hsImage.setVisibility(View.VISIBLE);
            vedioFile = new File(vedioFilePath);
            bitmapToPath();
        } else if (msgType == 1) {
            tvTitle.setText("动态");
            rlMsgInput.setVisibility(View.VISIBLE);
            hsImage.setVisibility(View.VISIBLE);
            rlSelectTime.setVisibility(View.GONE);
        } else if (msgType == 2) {
            if (role == 2) {
                tvTitle.setText("食谱");
                isRC = "R";
            } else {
                tvTitle.setText("课程");
                isRC = "C";
            }
            hsImage.setVisibility(View.VISIBLE);
            rlMsgInput.setVisibility(View.GONE);
            rlSelectTime.setVisibility(View.VISIBLE);
            tvTime.setText("请选择时间");
        } else if (msgType == 3) {
            tvTitle.setText("教务公告");
            rlMsgInput.setVisibility(View.VISIBLE);
            rlSelectTime.setVisibility(View.VISIBLE);
            hsImage.setVisibility(View.GONE);
            if (role == 2) {
                tvTime.setText("教务公告");
                isWork = 0;
                llClassSpinner.setVisibility(View.VISIBLE);
                llStudentSpinner.setVisibility(View.VISIBLE);
                getClasses();

            } else {
                tvTime.setText("请选择发布类型");
            }
        }
        initEmotion();
    }

    private void getClasses() {
        ActionHelp.gbbGetClassList(SendParentsCircleActivity.this, new ObjectCallback<List<SpinnerBean>>() {
            @Override
            public void onSuccess(List<SpinnerBean> response) {
                classes.clear();
                if (role == 3) {
                    classes.add(new SpinnerBean(Integer.parseInt(GbbPreferences.getClassId()), GbbPreferences.getClassName()));
                } else {
                    classes.add(new SpinnerBean(0, "全校"));
                    for (SpinnerBean bean : response) {
                        classes.add(new SpinnerBean(bean.getID(), bean.getNAME()));
                    }
                }
                ArrayAdapter<SpinnerBean> adapter = new ArrayAdapter<SpinnerBean>(SendParentsCircleActivity.this, android.R.layout.simple_spinner_item, classes);
                classSpinner.setAdapter(adapter);

                classSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        currentClassId = classes.get(position).getID();
                        getStudentsByClassId(currentClassId);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }

            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(SendParentsCircleActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "失败:" + code);
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<List<SpinnerBean>>() {
                }.getType();
            }
        });

    }

    private void getAdminRoels() {
        ActionHelp.gbbGetAdminroelList(SendParentsCircleActivity.this, new ObjectCallback<List<SpinnerBean>>() {
            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(SendParentsCircleActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "失败:" + code);
                }
            }

            @Override
            public void onSuccess(List<SpinnerBean> response) {
                adminroels.clear();
                adminroels.add(new SpinnerBean(0, "请选择"));
                for (SpinnerBean bean : response) {
                    adminroels.add(new SpinnerBean(bean.getID(), bean.getNAME()));
                }
                ArrayAdapter<SpinnerBean> adapter = new ArrayAdapter<SpinnerBean>(SendParentsCircleActivity.this, android.R.layout.simple_spinner_item, adminroels);
                classSpinner.setAdapter(adapter);
                classSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        currentAdminroelId = adminroels.get(position).getID();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }

            @Override
            public Type getType() {
                return new TypeToken<List<SpinnerBean>>() {
                }.getType();
            }
        });
    }

    private void getStudentsByClassId(int classId) {
        ActionHelp.gbbGetStudentsList(SendParentsCircleActivity.this, classId, new ObjectCallback<List<SpinnerBean>>() {
            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(SendParentsCircleActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "失败:" + code);
                }
            }

            @Override
            public void onSuccess(List<SpinnerBean> response) {
                students.clear();
                if (currentClassId == 0) {
                    students.add(new SpinnerBean(0, "全班"));
                } else {
                    students.add(new SpinnerBean(0, "全班"));
                    for (SpinnerBean bean : response) {
                        students.add(new SpinnerBean(bean.getID(), bean.getNAME()));
                    }
                }
                ArrayAdapter<SpinnerBean> adapter = new ArrayAdapter<SpinnerBean>(SendParentsCircleActivity.this, android.R.layout.simple_spinner_item, students);
                studentsSpinner.setAdapter(adapter);
                studentsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        currentStudentId = students.get(position).getID();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }

            @Override
            public Type getType() {
                return new TypeToken<List<SpinnerBean>>() {
                }.getType();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                mSelectPath.removeAll(selectedPictureAll);
                selectedPictureAll.addAll(mSelectPath);
                for (String p : mSelectPath) {
                    FriendImageView friendImageView = new FriendImageView(p);
                    friendLL.addView(friendImageView.getFriendView(), friendLL.getChildCount() - 1);
                    listFriend.add(friendImageView);
                }
                changeImageToBitmap(mSelectPath);
                notyPicChange();

            }
        }

    }

    private void success() {
        closeToast(1);
        tvSend.setEnabled(true);
        ToastUtil.showToast(context, "发布成功");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setResult(RESULT_OK);
                finish();
            }
        }, 800);
    }

    private LoadToast toast;
    private final String loadingLable = "正在发布...";

    /**
     * LoadToast是否显示中
     */
    public boolean isToastShowing() {
        return null != toast && toast.isShowing();
    }

    /**
     * 显示LoadToast
     */
    public void showToast() {
        if (null == toast) {
            toast = new LoadToast(this);
            toast.setText(loadingLable);
            toast.setTranslationY(200).setBackgroundColor(Color.parseColor("#FFFFFF")).setProgressColor(Color.BLUE);
        }
        if (!isToastShowing()) toast.show();
    }

    /**
     * 关闭LoadToast
     *
     * @param type 0:关闭，1：成功，-1：错误
     */
    public void closeToast(int type) {
        if (null == toast) return;
        switch (type) {
            case -1:
                toast.error();
                break;
            case 0:
                toast.close();
                toast = null;
                break;
            case 1:
                toast.success();
                break;
        }
    }

    public void viewClick(View v) {
        super.viewClick(v);
        switch (v.getId()) {
            case R.id.iv_common_back:
                finish();
                break;
            case R.id.btn_exp:
                if (ll_emotion_dashboard.getVisibility() == View.GONE) {
                    KeyBoardUtil.hide(edtContent);
                    ll_emotion_dashboard.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_common_leave_history:
                //发布消息
                if (msgType == 0) {
                    vedioSubmit();
                } else if (msgType == 1) {
                    submit();
                } else if (msgType == 2) {
                    courseSubmit();
                } else if (msgType == 3) {
                    if (isWork == 0) {
                        //教务公告
                        eduSubmit();
                    } else {
                        //工作汇报
                        workSubmit();
                    }
                }
                break;
            case R.id.iv_add_pic:
                if (msgType == 0) {
                    Intent intent = new Intent(this, SurfaceActivity.class);
                    intent.putExtra("type", 0);
                    intent.putExtra("vedioUrl", this.vedioFilePath);
                    startActivity(intent);
                } else if (msgType == 1) {
                    Intent intent = new Intent(this, MultiImageSelectorActivity.class);
                    // 是否显示拍摄图片
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, PIC_MAX_LENGTH);
                    // 选择模式
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    // 默认选择
                    if (selectedPictureAll != null && selectedPictureAll.size() > 0) {
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
                    }
                    startActivityForResult(intent, REQUEST_IMAGE);
                } else if (msgType == 2) {
                    Intent intent = new Intent(this, MultiImageSelectorActivity.class);
                    // 是否显示拍摄图片
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                    // 选择模式
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    // 默认选择
                    if (selectedPictureAll != null && selectedPictureAll.size() > 0) {
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
                    }
                    startActivityForResult(intent, REQUEST_IMAGE);
                }
                break;
            case R.id.rl_select_time:
                if (msgType == 2) {
                    dialog = new BottomSelectDialog(SendParentsCircleActivity.this, "本周", "下周", new BottomSelectDialog.onSelectSexListener() {
                        @Override
                        public void onSelect(int location) {
                            if (location == 0) {
                                isWeek = "T";
                                tvTime.setText("本周");
                            } else {
                                isWeek = "H";
                                tvTime.setText("下周");
                            }
                        }
                    });
                    dialog.show();
                } else if (msgType == 3) {
                    dialog = new BottomSelectDialog(SendParentsCircleActivity.this, "教务公告", "工作汇报", new BottomSelectDialog.onSelectSexListener() {
                        @Override
                        public void onSelect(int location) {
                            if (location == 0) {
                                tvTime.setText("教务公告");
                                isWork = 0;
                                llClassSpinner.setVisibility(View.VISIBLE);
                                llStudentSpinner.setVisibility(View.VISIBLE);
                                getClasses();
                            } else {
                                tvTime.setText("工作汇报");
                                isWork = 1;
                                llClassSpinner.setVisibility(View.VISIBLE);
                                llStudentSpinner.setVisibility(View.GONE);
                                getAdminRoels();
                            }
                        }
                    });
                    if (role == 3) {
                        dialog.show();
                    }
                }
                break;
            default:
                break;
        }
    }

    private void workSubmit() {
        if (StringUtil.isEmpty(edtContent.getText().toString().trim())) {
            ToastUtil.showToast(context, "发送内容不能为空哦");
            return;
        }

        if (currentAdminroelId == 0) {
            ToastUtil.showToast(context, "请选择汇报对象");
            return;
        }
        showToast();
        tvSend.setEnabled(false);
        ActionHelp.gbbAddEdu(SendParentsCircleActivity.this, edtContent.getText().toString(), currentAdminroelId, new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response) {
                success();
            }

            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(SendParentsCircleActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    closeToast(-1);
                    tvSend.setEnabled(true);
                    ToastUtil.showToast(SendParentsCircleActivity.this.context, "发布失败");
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });

    }

    private void eduSubmit() {
        if (StringUtil.isEmpty(edtContent.getText().toString().trim())) {
            ToastUtil.showToast(context, "发送内容不能为空哦");
            return;
        }
        String classId, studentId;
        if (currentClassId == 0) {
            classId = "";
        } else {
            classId = currentClassId + "";
        }
        if (currentStudentId == 0) {
            studentId = "";
        } else {
            studentId = currentStudentId + "";
        }
        showToast();
        tvSend.setEnabled(false);
        ActionHelp.gbbAddEdu(SendParentsCircleActivity.this, edtContent.getText().toString(), classId, studentId, new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response) {
                success();
            }

            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(SendParentsCircleActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    closeToast(-1);
                    tvSend.setEnabled(true);
                    ToastUtil.showToast(SendParentsCircleActivity.this.context, "发布失败");
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void courseSubmit() {
        if (StringUtil.isEmpty(isWeek)) {
            ToastUtil.showToast(SendParentsCircleActivity.this, "请选择时间");
            return;
        }
        if (currentPath.size() == 0) {
            ToastUtil.showToast(SendParentsCircleActivity.this, "请选择要上传的内容");
            return;
        }

        StringBuffer sb = new StringBuffer();
        sb.append(ImageUtils.bitmapToBase64(ImageUtils.getBitmapByPath(currentPath.get(0))) + "#jpg");

        showToast();
        tvSend.setEnabled(false);
        ActionHelp.gbbAddCourseOrRecipe(SendParentsCircleActivity.this, sb.toString(), isRC, isWeek, new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response) {
                success();
            }

            @Override
            public void onError(int code) {
                closeToast(-1);
                tvSend.setEnabled(true);
                ToastUtil.showToast(SendParentsCircleActivity.this.context, "发布失败");
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object itemAdapter = parent.getAdapter();

        if (itemAdapter instanceof EmotionGvAdapter) {
            // 点击的是表情
            EmotionGvAdapter emotionGvAdapter = (EmotionGvAdapter) itemAdapter;

            if (position == emotionGvAdapter.getCount() - 1) {
                // 如果点击了最后一个回退按钮,则调用删除键事件
                edtContent.dispatchKeyEvent(new KeyEvent(
                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
            } else {
                // 如果点击了表情,则添加到输入框中
                String emotionName = emotionGvAdapter.getItem(position);

                // 获取当前光标位置,在指定位置上添加表情图片文本
                int curPosition = edtContent.getSelectionStart();
                StringBuilder sb = new StringBuilder(edtContent.getText().toString());
                sb.insert(curPosition, emotionName);

                // 特殊文字处理,将表情等转换一下
                edtContent.setText(StringUtils.getEmotionContent(
                        this, edtContent, sb.toString()));

                // 将光标设置到新增完表情的右侧
                edtContent.setSelection(curPosition + emotionName.length());
            }

        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            ll_emotion_dashboard.setVisibility(View.GONE);
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
//            ToastUtil.showToast(activity, "键盘关闭了");
        }
    }

    private class FriendImageView
            implements
            View.OnClickListener {
        private View friendView;
        public ImageView friendImg;
        public ImageView deleteImg;

        public String imagePath = "";

        public FriendImageView(String imagePath) {
            friendView = LayoutInflater.from(context).inflate(R.layout.sendmsg_item_img, friendLL, false);
            friendImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_img);
            friendImg.setOnClickListener(this);
            deleteImg = (ImageView) friendView.findViewById(R.id.new_interation_center_user_publish_friend_item_delete);
            deleteImg.setOnClickListener(this);
            this.imagePath = imagePath;
            ImageLoaderUtil.loadLocalUrl(imagePath, friendImg);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.new_interation_center_user_publish_friend_item_delete:
                    remove();
                    break;
                case R.id.new_interation_center_user_publish_friend_item_img:
                    Intent atlasSeeIntent = new Intent(SendParentsCircleActivity.this, AtlasSeeActivity.class);
                    atlasSeeIntent.putExtra(Const.FROM_TYPE, Const.NI_FROM_LOCALURL);
                    atlasSeeIntent.putExtra(Const.NI_ATLASSEE_URL, selectedPictureAll);
                    atlasSeeIntent.putExtra(Const.NI_POSITION, listFriend.indexOf(this));
                    SendParentsCircleActivity.this.startActivity(atlasSeeIntent);
                    break;
            }

        }

        public void remove() {
            listFriend.remove(this);
            selectedPictureAll.remove(imagePath);
            friendLL.removeView(friendView);
            notyPicChange();
        }

        public View getFriendView() {
            return this.friendView;
        }

    }
}
